<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>nav菜单项下划线跟随鼠标移动</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            list-style: none;
        }

        html, body {
            height: 100%;
        }

        #wrapper {
            position: relative;
        }

        ul {
            display: flex;
        }

        li {
            margin: 0 10px;
            padding: 20px;
            cursor: pointer;
        }

        span {
            position: absolute;
            width: 100px;
            height: 3px;
            bottom: 0;
            background-color: aquamarine;
        }
    </style>
</head>
<body>
<div id="wrapper">
    <ul>
        <li>item1</li>
        <li>item22</li>
        <li>item333</li>
        <li>item4444</li>
        <li>item55555</li>
    </ul>
    <span></span>
</div>

<script>
    let wrapper = document.getElementById("wrapper")
    let ul = document.getElementsByTagName("ul")[0]
    let span = document.querySelector("#wrapper span")

    span.style.width = ul.children[0].offsetWidth + 20 + "px"
    ul.addEventListener("mouseenter", e => {
        if (e.target.tagName === "LI") {
            span.style.width = window.getComputedStyle(e.target).width
            span.style.transform = `translateX(${e.target.offsetLeft}px)`
            span.style.transition = ".3s"
        }
    }, true)
</script>
</body>
</html>